package com.yuyou.fn.platform.service.impl;

import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.VerifyCodeUtils;
import com.yuyou.fn.platform.service.ICaptchaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

/**
 * Created by wens on 16-11-15.
 */
@Service
public class CaptchaServiceImpl implements ICaptchaService {

    private final static String CAPTCHA_KEY="CAPTCHA:%s" ;

    private final static String CAPTCHA_OPS_STAT_KEY="CAPTCHA_OPS_STAT:%s:%s" ;

    @Resource
    private RedisTemplate redisTemplate ;

    @Override
    public void outputImage(int w, int h, OutputStream os) throws IOException {
        String code = VerifyCodeUtils.generateVerifyCode(4);
        VerifyCodeUtils.outputImage(w,h, os,code );
        redisTemplate.opsForValue().set(String.format(CAPTCHA_KEY,code.toLowerCase()) , code , 10, TimeUnit.MINUTES );
    }

    @Override
    public void verifyCode(String code) {

        if(StringUtils.isEmpty(code)){
            throw new BusException("验证码不能为空");
        }
        code = code.toLowerCase().trim();
        String val = (String)redisTemplate.opsForValue().get(String.format(CAPTCHA_KEY, code));
        if(val == null || ( code != null && !code.equalsIgnoreCase(val) ) ){
            throw new BusException("输入的验证码不正确或已过期") ;
        }

        //清除
        redisTemplate.delete(String.format(CAPTCHA_KEY, code));

    }

    @Override
    public void cleanOptStat(String uid, String ops) {
        redisTemplate.delete(String.format(CAPTCHA_OPS_STAT_KEY, uid ,ops ));
    }

    @Override
    public Long opsStat(String uid, String ops) {
        Long count  = redisTemplate.opsForValue().increment(String.format(CAPTCHA_OPS_STAT_KEY, uid ,ops ) , 1 );
        redisTemplate.expire(String.format(CAPTCHA_OPS_STAT_KEY, uid ,ops ) , 30 ,TimeUnit.MINUTES );
        return count ;
    }

    @Override
    public boolean needVerifyCode(String uid, String ops, int threshold) {
        String val = (String)redisTemplate.opsForValue().get(String.format(CAPTCHA_OPS_STAT_KEY, uid ,ops ));
        if(val == null || Long.parseLong(val) < threshold ){
            return false ;
        }
        return true;
    }

}
